package com.framework.buss.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.framework.buss.ai.mapper.RedisKeyMapper;
import com.framework.common.model.RedisKey;
import com.framework.common.util.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author zhangzhg
 */
@Log4j2
@Component
public class IncrementIdUtil {
    private final String suffix = "_rule";

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedisKeyMapper redisKeyMapper;

    /**
     * 初始化数据
     */
    @PostConstruct
    public void init() {
        List<RedisKey> list = redisKeyMapper.selectList(null);
        list.forEach(it -> {
            if (!redisUtil.hasKey(it.getKey())) {
                redisUtil.set(it.getKey(), it.getValue());
                redisUtil.set(it.getKey().concat(suffix), it.getRule());
                log.info("初始化编码生成规则(RedisKey):{}", it.getKey());
            }
        });
    }

    /**
     * 使用redis生成， 多个人同时新增的时候id不会重复
     * @param key 生成规则key
     * @return 按规则返回下一个key
     */
    public String getCode(String key) {
        long value = redisUtil.incr(key, 1);
        String rule = redisUtil.get(key.concat(suffix));
        if (ObjectUtils.isEmpty(rule)) {
            log.warn("自动生成code，sys_redis_key表数据没有初始化。");
            return String.valueOf(value);
        }
        String result = String.format(rule, value);

        // 修改一下数据库的值。数据迁移的时候防止数据新增失败。
        QueryWrapper<RedisKey> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(RedisKey::getKey, key);
        RedisKey item = redisKeyMapper.selectOne(queryWrapper);
        item.setValue(Integer.parseInt(String.valueOf(value)));
        redisKeyMapper.updateById(item);

        return result;
    }
}
